package org.example.javachatroom.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.javachatroom.mapper.MessageMapper;
import org.example.javachatroom.mapper.MessageSessionMapper;
import org.example.javachatroom.model.Friend;
import org.example.javachatroom.model.MessageSession;
import org.example.javachatroom.model.MessageSessionUserItem;
import org.example.javachatroom.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class MessageSessionController {
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;

    /**
     *获取会话列表
     * @param request
     * @return
     */
    @GetMapping("/sessionList")
    @ResponseBody
    public Object getMessageSessionList(HttpServletRequest request){
        List<MessageSession> messageSessionList = new ArrayList<>();
        //1、获取当前用户的userId（从spring的session中获取）
        HttpSession session = request.getSession(false);
        if(session == null){
            System.out.println("[getMessageSessionList] 获取session失败！");
            return messageSessionList;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            System.out.println("[getMessageSessionList] 用户未登录！");
            return messageSessionList;
        }
        //2、根据userId查询当前用户有哪些会话id
            List<Integer> sessionIdList = messageSessionMapper.getSessionIdsByUserId(user.getUserId());
            for (int id : sessionIdList) {
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(id);
            //3、遍历会话id，查询出每个会话里涉及到的好友都有谁
            List<Friend> friends = messageSessionMapper.getFriendBySessionId(id,user.getUserId());
            messageSession.setFriends(friends);
            //4、遍历会话id，查询出每个会话的最后一条消息
            //有可能出现按照会话id查不到消息的情况
            String lastMessage = messageMapper.getLastMessageBySessionId(id);
            if(lastMessage == null){
                messageSession.setLastMessage("");
            }else {
                messageSession.setLastMessage(lastMessage);
            }
            messageSessionList.add(messageSession);
        }
        //最终目标就是构造出一个MessageSession对象数组
        return messageSessionList;
    }

    //返回sessionId
    @PostMapping("/session")
    @ResponseBody
    @Transactional
    public Object addMessageSession(int toUserId, @SessionAttribute("user")User user){
        HashMap<String,Integer> hashMap = new HashMap<>();
        //进行数据处理的插入操作
        //1、先给MessageSession表里插入记录，使用这个参数的目的主要是为了获取到会话的sessionid
        //换而言之，MessageSession里的friends和lastTime属性此处用不上
        MessageSession messageSession = new MessageSession();
        messageSessionMapper.addMessageSession(messageSession);
        //2、给message_session_user表插入记录
        //此处之创建一个item，设置不同属性，分两次进行插入也是完全可以的，但是这么搞不太好
        //原则：一个方法只做一件事，一个变量只做一件事
        MessageSessionUserItem item1 = new MessageSessionUserItem();
        item1.setSessionId(messageSession.getSessionId());
        item1.setUserId(user.getUserId());
        messageSessionMapper.addMessageSessionUser(item1);
        //3、给message_session_user表插入记录
        MessageSessionUserItem item2 = new MessageSessionUserItem();
        item2.setSessionId(messageSession.getSessionId());
        item2.setUserId(toUserId);
        messageSessionMapper.addMessageSessionUser(item2);
        System.out.println("[addMessageSession] 新增会话成功！ sessionId = "+messageSession.getSessionId()
        +" userId1 = "+user.getUserId()+" userId2 = "+ toUserId);
        hashMap.put("sessionId", messageSession.getSessionId());
        //返回的对象是一个普通对象也可以，或者是一个Map也可以，jackson都能进行处理
        return hashMap;
    }
}
